from __future__ import absolute_import
from __future__ import print_function
import os
import sys
import optparse
from controlModel import controlModel

if 'SUMO_HOME' in os.environ:
    tools = os.path.join(os.environ['SUMO_HOME'], 'tools')#将路径和文件名合并
    sys.path.append(tools)# 添加至python的解释器路径
else:
    sys.exit("please declare environment variable 'SUMO_HOME'")#退出python



import traci
import random
from sumolib import checkBinary

def get_options():#增加选择哪种进行仿真 sumo或者sumo_gui
    optParser = optparse.OptionParser()
    optParser.add_option("--nogui", action="store_true",
                         default=False, help="run the commandline version of sumo")
    options, args = optParser.parse_args()
    return options

def run():
    for carID in traci.vehicle.getIDList():
        p = 0.5 #驾驶员反应时间
        if traci.vehicle.getLanePosition(carID): #车辆在车道上进行控制
            lane = traci.vehicle.getLaneID(carID)
            changeLane = controlModel(carID).changeLane()
            if lane == "gneE1_0":#如果在最右侧车道
                if changeLane[0]:#如果进行换道，则换至中间车道，换道时间为10s，下同
                    traci.vehicle.changeLane(carID, 1, 10)
                else:#如果不进行换道，则更新速度与位置，下同
                    speed_next = controlModel(carID).speed_generate()
                    traci.vehicle.setSpeed(carID, speed_next)
                    traci.vehicle.moveTo(carID, lane, speed_next*(1+p)+traci.vehicle.getLanePosition(carID))
            elif lane == "gneE1_2":#如果在最左侧车道
                if changeLane[0]:
                    traci.vehicle.changeLane(carID, 1, 10)
                else:
                    speed_next = controlModel(carID).speed_generate()
                    traci.vehicle.setSpeed(carID, speed_next)
                    traci.vehicle.moveTo(carID, lane, speed_next*(1+p)+traci.vehicle.getLanePosition(carID))
            elif lane == "gneE1_1":#如果在最中间车道
                if changeLane[0]:
                    if changeLane[1]:
                        traci.vehicle.changeLane(carID, 2, 10)
                    elif changeLane[2]:
                        traci.vehicle.changeLane(carID, 0, 10)
                else:
                    speed_next = controlModel(carID).speed_generate()
                    traci.vehicle.setSpeed(carID, speed_next)
                    traci.vehicle.moveTo(carID, lane, speed_next*(1+p) + traci.vehicle.getLanePosition(carID))

if __name__ == "__main__":
    options = get_options()

    if options.nogui:#选择仿真
        sumoBinary = checkBinary('sumo')
    else:
        sumoBinary = checkBinary('sumo-gui')

    traci.start([sumoBinary, "-c", "D:/a_desktop/sumo_study/sumo_sduty/buslane.sumocfg", "--tripinfo-output", "tripinfo.xml"])  # 多次调用
    for step in range(0, 3600):
        while traci.simulation.getMinExpectedNumber() > 0:
            traci.simulationStep()
            run()
    traci.close()
    sys.stdout.flush()